from base import By, sleep, webdriver
# 导入动作链条模块
from selenium.webdriver.common.action_chains import ActionChains
import os.path


class MouseOperation:
    def __init__(self):
        self.driver = webdriver.Chrome()
        self.driver.get('https://sahitest.com/demo/clicks.htm')

    def click(self):
        sleep(2)
        # 找到点击按钮的位置
        btn = self.driver.find_element(By.XPATH, '//form/input[3]')
        # 创建动作链条对象
        ac = ActionChains(driver=self.driver)
        # 给ac选择click方法后,调用perform方法才会执行
        ac.click(btn).perform()

    def context_click(self):  # 右击
        sleep(2)
        btn = self.driver.find_element(By.XPATH, '//form/input[4]')
        ac = ActionChains(self.driver)
        ac.context_click(btn).perform()

    def double_click(self):  # 双击
        sleep(2)
        btn = self.driver.find_element(By.XPATH, '//form/input[2]')
        ac = ActionChains(self.driver)
        ac.double_click(btn).perform()

    def drag_and_drop(self):  # 拖动(拖放)
        self.driver.get('https://sahitest.com/demo/dragDropMooTools.htm')
        source = self.driver.find_element(By.ID, 'dragger')
        target = self.driver.find_element(By.XPATH, '/html/body/div[4]')
        ac = ActionChains(self.driver)
        ac.drag_and_drop(source, target).perform()

    def mouseover(self):  # 鼠标悬停
        self.driver.get('https://sahitest.com/demo/mouseover.htm')
        sleep(2)
        div = self.driver.find_element(By.XPATH, '/html/body/a[1]/span')
        ac = ActionChains(self.driver)
        ac.move_to_element(div).perform()

    def click_and_hold(self):
        # 拼接绝对路径.(需要html在同级目录)
        url = 'file:///' + os.path.abspath('html') + '/mouse_hold.html'
        self.driver.get(url)
        sleep(2)
        btn = self.driver.find_element(By.ID, 'btn1')
        ac = ActionChains(self.driver)
        ac.click_and_hold(btn).perform()

    def quit(self):
        sleep(3)
        self.driver.quit()


if __name__ == '__main__':
    mouse = MouseOperation()
    # mouse.click()
    # mouse.context_click()
    # mouse.double_click()
    # mouse.drag_and_drop()
    # mouse.mouseover()
    mouse.click_and_hold()
    mouse.quit()
